from app import db
from mongoengine import Q
import time

class IotData(db.Document):
    humidity = db.IntField()
    isHuman = db.StringField()
    topic = db.StringField()
    ts = db.FloatField()
    temperature = db.FloatField()
    meta = {'collection': 'IotDatas', 'strict': False}

    @classmethod
    def get_recent_data(cls, room, day=1, page=1, size=20):
        now = time.time()
        result = cls.objects(Q(topic__contains=str(room)) & Q(ts__gte=now-day*24*60*60))
        return result[page*size-size: page*size]

    def json(self):
        return {
            "humidity": float(self.humidity) / 100,
            "isHuman": False if self.isHuman == 'false' else True,
            "temperature": self.temperature,
            "ts": self.ts,
            "room": str(self.topic).split('/')[1]
        }
